import { Injectable } from '@angular/core';
import { Action, State, StateContext } from '@ngxs/store';
import { UserAction } from '.';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';
import { PasswordModalComponent } from '../../pages/user/password-modal/password-modal.component';
import { AuthService } from '../../shared/auth/auth.service';
import { tap } from 'rxjs';

export interface UserStateModel {
  passwordForm: any;
}

@State<UserStateModel>({
  name: 'user',
  defaults: {
    passwordForm: {},
  },
})
@Injectable({
  providedIn: 'root',
})
export class UserState {

  constructor(
      private modal: NzModalService,
      private message: NzMessageService,
      private auth: AuthService,
  ) {
  }

  @Action(UserAction.PasswordModal)
  PasswordModal() {
    this.modal.create({
      nzTitle: '修改密码',
      nzContent: PasswordModalComponent,
      nzComponentParams: {},
      nzMaskClosable: false,
      nzStyle: {
        width: '600px',
      },
      nzFooter: [
        {
          label: '确定',
          type: 'primary',
          disabled: (i) => {
            return !i || !i.validateForm.dirty || i.validateForm.invalid;
          },
          onClick: (i) => i?.submitForm(),
        },
      ],
      nzOnOk: () => {
        this.message.success(`保存成功`);
      },
    });
  }

  @Action(UserAction.ChangePassword)
  ChangePassword(ctx: StateContext<UserStateModel>) {
    let state = ctx.getState();
    let passwordForm = state.passwordForm;
    if (!passwordForm.dirty || passwordForm.status === 'INVALID') {
      return;
    }
    return this.auth.changePassword(passwordForm.model).pipe(tap({
      next: () => {
        this.message.success(`密码修改成功，请重新登录`);
      },
      error: e => {
        if (!e.ok && e.status === 500 && !!e.error.message) {
          this.message.error(`${e.error.message}`);
        } else {
          this.message.error(`密码修改失败`);
        }
      },
    }));
  }
}
